<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Portal extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		
		$this->load->config();
		$this->load->config('stareit', TRUE);
		$this->load->config('rss', TRUE);
		$this->load->library('security');
		$this->load->library('session');
		$this->load->library('facebookapi');
		$this->load->library('googleapi');
		$this->load->model('stareit/connection');
	}
	
	function update_simplepie_cache(){
		$this->load->library('simplepie'); 
        $urls = $this->connection->fetchURLs();
        $cache_location = 'application/cache/simplepie';  //  change to your cache location 
        
        $this->simplepie->set_feed_url($urls);
        $this->simplepie->set_cache_location($cache_location);
        $this->simplepie->set_cache_duration(0);   // force cache to update immediatlely 
        $this->simplepie->set_timeout(5);   // optional, if you have a lot of feeds a low timeout may be necessary 
        $this->simplepie->init();
		echo 'cache updated!';
	}

	function index()
	{	
		//echo 'timestamp:'.date("G:i:s",time())."<br>";
		$get_data = $this->input->get(NULL, TRUE); // returns all POST items with XSS filter
        if (isset($get_data['code'])) {
            $user = $this->facebookapi->login();
        }
		else $user = array();
		
		$session_data = $this->session->all_userdata();//get session
		
		
		//$categories = array();
		$default_feed_arr = array();
		$urlMappingTitle = array();
        
		$this->get_mapping_data();
		$user_data = $this->session->userdata('user_data');//get session
		
		$data = array();
		$header_data = array();
		$header_data['app_id'] = $this->config->item('fb_app_id', 'stareit');
		//$header_data['category_form'] = $this->get_category_form(&$user_data);
		$header_data['login_form'] = $this->get_login_form(&$session_data);
		
		//echo $this->load->view('stareit/header', $header_data ,true);
		$this->load->view('stareit/header', $header_data);
		
		/*
		 * sidebar
		 */
		$data['sidebar'] = $this->load->view('stareit/sidebar', '',true);
		//$this->load->view('stareit/sidebar', '');
		$contents = $this->get_content(&$user_data['MAPPING_DATA']['default_feed_arr'],0,false);
		$data['content'] = $contents['msg'];
		$data['next_page'] = $contents['next_page'];
		//echo $this->load->view('stareit/wrapper', $data ,true);
		//echo $this->load->view('stareit/footer', '' ,true);
		$this->load->view('stareit/wrapper', $data );
		$this->load->view('stareit/footer', '' );
	}
	
	function get_login_form($session_data){
		if($this->facebookapi->checkLoginStatus()){
			$data = array();
			$data['profile_picture'] = $this->config->item('fb_graph_api_url', 'stareit').$session_data['user_data']['LOGIN_INFO']['id'].'/picture';
			$data['user_name'] = $session_data['user_data']['LOGIN_INFO']['name'];
			return $this->load->view('stareit/login_already', $data ,true);
		}
		else{
			return $this->load->view('stareit/not_login_yet', '' ,true);
		}
	}
	
	function get_category_form(){
		$user_data = $this->session->userdata('user_data');//get session
		$data = array();
		if(!isset($user_data['LOGIN_INFO']['id'])){ // not login yet
			$data['categories'] = $this->config->item('sub_category', 'rss');
			echo $this->load->view('stareit/category_form', $data ,true);
		}
		else{
			$uncategorize = '未分類';
			$data['categories'] = $user_data['CATEGORY_DATA']; // user customize categories
			/*
			 * 把未分類移至array 最後方
			 */
			$temp = $data['categories'][$uncategorize];
			unset($data['categories'][$uncategorize]);
			$data['categories'][$uncategorize] = $temp;
			//echo "<pre>";print_r($data);echo "</pre>";
			echo $this->load->view('stareit/category_form', $data ,true);
		} 
	}
	
	function get_hot_searches(){
		$user_data = $this->session->userdata('user_data');//get session
		$data = array();
		
		$data['hot_searches'] = $this->googleapi->getTopSearchKeywords();
		//var_dump($search_keywords);
		
		echo $this->load->view('stareit/hot_searches', $data ,true);
	}
	
	function get_blog_results(){
		$post_data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$this->load->library('googleapi');
		$json = $this->googleapi->getBlogResults($post_data['start'],$post_data['q']);
		
        $next_start = '';
        $previous_start = '';
        $currentPageIndex = @$json->responseData->cursor->currentPageIndex;
        
        if (isset($json->responseData->cursor->pages[$currentPageIndex + 1])) {
            $next_start = @$json->responseData->cursor->pages[$currentPageIndex + 1]->start;
        
        }
        
        if (isset($json->responseData->cursor->pages[$currentPageIndex - 1])) {
            $previous_start = @$json->responseData->cursor->pages[$currentPageIndex - 1]->start;
        }
        
        
        $results = @$json->responseData->results;
        //echo "<pre>";print_r($results);echo "</pre>";
		$msg = '';
        foreach (@$results as $key=>$data) {
        	$msg .= '<div class="content">';
            $msg .= '<h2><a href="'.$data->postUrl.'" target="_blank">'.$data->title.'</a></h2>';
            $msg .= '<p>'.strip_tags($data->content).'</p>';
			$msg .= '</div>';
        }
       
		if ($next_start != '') {	
			$next_page = '<a href="javascript:;" onclick="searchFeed(\''.$next_start.'\',\''.$post_data['q'].'\')" id="next">more</a>';
		}
		else{
			$next_page = '';
		}
		
		echo json_encode(array('msg'=>$msg,'next_page'=>$next_page));
	}
	
	function get_mapping_data($selected_urls = array()){
		$default_feed_arr = array();
		$user_data = $this->session->userdata('user_data');//get session
		if (!isset($user_data['MAPPING_DATA']) || !isset($user_data['CATEGORY_DATA'])) {
			/*for not login*/
            $this->set_mapping_data();
		}
		return;
	}
	
	function set_mapping_data($reset = false){
		$sub_category = array();
		$urlMappingTitle = array();
		$default_feed_arr = array();
		$user_data = $this->session->userdata('user_data');//get session
		$mapping_data = array();
		$category_data = array();
        if (!isset($user_data['MAPPING_DATA']) || !isset($user_data['CATEGORY_DATA']) || $reset) {
            if (isset($user_data['LOGIN_INFO']['id'])) {//already login
                $sub_category = $this->connection->fetchSubCategory($user_data['LOGIN_INFO']['id']);
                $sub_category = urldecode($sub_category);
                $sub_category = json_decode($sub_category, true);
                /*for already login*/
                foreach ($sub_category as $category_key=>$feed_datas) {
                    foreach ($feed_datas as $feed) {
                        $default_feed_arr[] = $feed['url'];
                        $url_mapping_title['feed:'.$feed['url']] = $feed['title'];
                    }
                }
				$user_data['MAPPING_DATA']['default_feed_arr'] = $default_feed_arr;
                $user_data['MAPPING_DATA']['url_mapping_title'] = $url_mapping_title;
				$user_data['CATEGORY_DATA'] = $sub_category;
				
            } else { // not login yet
                /*for not login*/
                $default_feed = $this->config->item('sub_category', 'rss');
                foreach ($default_feed as $category_key=>$feed_datas) {
                    foreach ($feed_datas as $feed) {
                        $default_feed_arr[] = $feed['url'];
						$url_mapping_title['feed:'.$feed['url']] = $feed['title'];
                    }
                }
                $user_data['MAPPING_DATA']['default_feed_arr'] = $default_feed_arr;
                $user_data['MAPPING_DATA']['url_mapping_title'] = $url_mapping_title;
				$user_data['CATEGORY_DATA'] = $default_feed;
            }
			
			$this->session->set_userdata('user_data',$user_data);
        }
	}
	
	function get_more_feed(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$data['url'] = explode('|',$data['url']);
		echo $this->get_content($data['url'],$data['offset'],true);
	}
	
	function change_feed_source(){
		$url = array();
		$urlMappingTitle = array();
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
        $this->get_mapping_data();
        $user_data = $this->session->userdata('user_data');//get session
        //echo "<pre>";print_r($user_data);echo "</pre>";
        if (isset($user_data['CATEGORY_DATA'][$data['category']]) && !empty($user_data['CATEGORY_DATA'][$data['category']])) {
            foreach ($user_data['CATEGORY_DATA'][$data['category']] as $key=>$feed) {
                $url[] = $feed['url'];
            }
            echo $this->get_content($url, '', true);
        } else {
            echo json_encode(array('status'=>false, 'msg'=>'此分類尚無內容', 'next_page'=>''));
        }

	}
	
	function get_content($url,$offset = 0,$jsonflag = false){
		$user_data = $this->session->userdata('user_data');//get session
		$this->load->library('simplepie');
		
		$this->simplepie->set_feed_url($url);
		$this->simplepie->set_cache_duration(3600);
		$this->simplepie->set_timeout(-1); 
		$this->simplepie->init();
		$this->simplepie->handle_content_type();
		
		$max = $this->simplepie->get_item_quantity();
		
		$length = $this->config->item('rss_feed_count', 'rss');//一次抓幾則回來
		
		$start_offset = $offset*$length;//start index
		$offset++;//讓下一次抓資料用
		
		$msg = '';
		foreach($this->simplepie->get_items($start_offset,$length) as $item){
			$msg .= '<div class="content">';
			$msg .= '<h2 style="position:relative;margin:0;padding:0 0 31px;"><a href="'.$item->get_permalink().'" target="_blank">'.($item->get_title()).'</a>';
			$msg .= '<div class="feed_share" style="display: none;"><a target="_blank"href="https://www.facebook.com/sharer/sharer.php?src=bm&u='.urlencode($item->get_permalink()).'&t='.$item->get_title().'" ><img src="/images/public/facebook_button.png"/></a></div>';
			$msg .= '</h2>';
			//$msg .= '<span class="date">'.$item->get_date().'</span>';
			$matches = array();
			$pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/'; 
			preg_match_all($pattern, $item->get_content(), $matches); 
			
			if(!empty($matches[0])){//this article without images
				$msg .= '<img '.$matches[0][0].' width="200" height="200"/>';	
			}
			else{
				$msg .= '<p>'.(str_replace('<p></p>','',$item->get_content())).'</p>';
			}
			if(isset($user_data['MAPPING_DATA']['url_mapping_title'][$item->get_feed()->subscribe_feed()])){
				$msg .= '<div class="feed_title">'.$user_data['MAPPING_DATA']['url_mapping_title'][$item->get_feed()->subscribe_feed()].'</div>';
				//echo 	$urlMappingTitle[$item->get_feed()->subscribe_feed()];
			}
			else $msg .= '<div class="feed_title">'.($item->get_feed()->get_title()).'</div>';
			
			$msg .= '</div>';
		}
		
		
		
		$next_page = '';
		$url_str = '';
		if(is_array($url)){
			foreach($url as $site){
				$url_str .= $site.'|';
			}
			$url_str = substr($url_str,0,-1);
		}
		else{
			$url_str = $url;	
		}
		
		if(($start_offset+$length) < $max){	
			$next_page = '<a href="javascript:;" onclick="getMoreFeed(\''.$url_str.'\',\''.$offset.'\')" id="next">more</a>';
		}
		else{
			$next_page = '';
		}
		/*
		print microtime(true) - $t;
		echo "<br>";exit;
		*/
		//echo 'timestamp:'.date("G:i:s",time());
		
		if($jsonflag == true){
			return json_encode(array('status'=>true,'msg'=>$msg,'next_page'=>$next_page));
		}
		else return array('status'=>true,'msg'=>$msg,'next_page'=>$next_page);	
	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */